<template>
  <div class="scheduling-management">
    <h1 class="page-title">排班管理</h1>
    <div class="filter-bar">
      <div class="filter-item">
        <label for="date-filter">选择日期:</label>
        <input id="date-filter" type="date" v-model="filters.date">
      </div>
      <div class="filter-item">
        <label for="keyword-filter">搜索:</label>
        <input id="keyword-filter" type="text" v-model="filters.keyword" placeholder="按姓名、班次、地点搜索">
      </div>
      <button class="btn btn-primary" @click="applyFilters">应用筛选</button>
      <button class="btn btn-secondary" @click="resetFilters">重置</button>
    </div>

    <div class="action-bar">
      <button class="btn btn-primary" @click="openAddModal">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
        <span>添加排班</span>
      </button>
      <button class="btn btn-secondary" @click="exportToExcel">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
        <span>导出排班表</span>
      </button>
    </div>

    <div class="table-container">
      <table>
        <thead>
        <tr>
          <th>班次名称</th>
          <th>日期</th>
          <th>时间</th>
          <th>排班人员</th>
          <th>地点/区域</th>
          <th>任务描述</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-if="paginatedSchedules.length === 0">
          <td colspan="7" class="empty-data">根据当前筛选条件，暂无数据</td>
        </tr>
        <tr v-for="schedule in paginatedSchedules" :key="schedule.shiftId">
          <td>{{ schedule.shiftName }}</td>
          <td>{{ schedule.date }}</td>
          <td>{{ formatTimeRange(schedule) }}</td>
          <td>{{ schedule.officerNames.join('、') }}</td>
          <td>{{ schedule.location }}</td>
          <td>{{ schedule.taskDescription }}</td>
          <td>
            <button class="btn-action btn-edit" @click="openEditModal(schedule)">编辑</button>
            <button class="btn-action btn-delete" @click="deleteSchedule(schedule.shiftId)">删除</button>
          </td>
        </tr>
        </tbody>
      </table>
    </div>

    <Pagination
      v-if="filteredSchedules.length > itemsPerPage"
      :current-page="currentPage"
      :total-pages="totalPages"
      @page-changed="handlePageChange"
    />

    <AiSuggestionCard :suggestions="aiSuggestions" />
    <SchedulingFormModal
      v-if="isModalOpen"
      :is-edit-mode="isEditMode"
      :initial-data="selectedSchedule"
      :police-list="policeList"
      @close="closeModal"
      @save="saveSchedule"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue';
import SchedulingFormModal from './SchedulingFormModal.vue';
import AiSuggestionCard from './AiSuggestionCard.vue';
import Pagination from '@/components/Pagination.vue';
import * as XLSX from 'xlsx';
import api from '@/utils/axios';

const API_BASE_URL = 'http://localhost:8080/api/auth';

const policeList = ref<any[]>([]);
const scheduleList = ref<any[]>([]);
const aiSuggestions = ref<any[]>([]);

// 获取所有警员信息
const getPoliceList = async () => {
  try {
    const response = await api.get(`${API_BASE_URL}/officers`);
    policeList.value = response.data.data;
  } catch (error) {
    console.error('获取警员列表失败:', error);
  }
};

// 获取所有排班信息并打印
const getAllShifts = async () => {
  try {
    const response = await api.get(`${API_BASE_URL}/shifts`);
    scheduleList.value = response.data;

    console.groupCollapsed('【获取排班列表】');
    console.log('排班列表长度:', scheduleList.value.length);
    if (scheduleList.value.length > 0) {
      console.log('第一个排班数据:', scheduleList.value[0]);
      console.log('所有排班数据预览:', scheduleList.value.slice(0, 3));
    } else {
      console.log('当前没有排班数据');
    }
    console.groupEnd();
  } catch (error) {
    console.error('获取排班列表失败:', error);
  }
};

onMounted(() => {
  getPoliceList();
  getAllShifts();
  const storedSuggestions = localStorage.getItem('aiSuggestions');
  if (storedSuggestions) {
    aiSuggestions.value = JSON.parse(storedSuggestions);
  }
});

// 筛选逻辑
const filters = reactive({ date: '', keyword: '' });
const activeFilters = reactive({ date: '', keyword: '' });

const applyFilters = () => {
  activeFilters.date = filters.date;
  activeFilters.keyword = filters.keyword.trim().toLowerCase();

  console.groupCollapsed('【应用筛选条件】');
  console.log('筛选日期:', activeFilters.date);
  console.log('筛选关键词:', activeFilters.keyword);
  console.groupEnd();
};

const resetFilters = () => {
  filters.date = '';
  filters.keyword = '';
  applyFilters();

  console.log('【重置筛选条件】');
};

const filteredSchedules = computed(() => {
  const result = scheduleList.value.filter(s => {
    const dateMatch = !activeFilters.date || s.date === activeFilters.date;
    const keywordMatch = !activeFilters.keyword ||
      s.shiftName.toLowerCase().includes(activeFilters.keyword) ||
      s.location.toLowerCase().includes(activeFilters.keyword) ||
      s.officerNames.some(name => name.toLowerCase().includes(activeFilters.keyword));
    return dateMatch && keywordMatch;
  });

  console.groupCollapsed('【筛选后排班数据】');
  console.log('筛选后数量:', result.length);
  console.groupEnd();

  return result;
});

// 分页逻辑
const currentPage = ref(1);
const itemsPerPage = ref(10);
const totalPages = computed(() => Math.ceil(filteredSchedules.value.length / itemsPerPage.value));
const paginatedSchedules = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage.value;
  const end = start + itemsPerPage.value;
  const result = filteredSchedules.value.slice(start, end);

  console.groupCollapsed(`【第${currentPage.value}页排班数据】`);
  console.log('当前页数据数量:', result.length);
  console.groupEnd();

  return result;
});

const handlePageChange = (page: number) => {
  currentPage.value = page;

  console.log(`【切换到第${page}页】`);
};

watch(activeFilters, () => {
  currentPage.value = 1;

  console.log('【筛选条件变化，重置到第1页】');
});

// 弹窗逻辑
const isModalOpen = ref(false);
const isEditMode = ref(false);
const selectedSchedule = ref<any>(null);

const openAddModal = () => {
  isEditMode.value = false;
  selectedSchedule.value = null;
  isModalOpen.value = true;

  console.log('【打开添加排班弹窗】');
};

const openEditModal = (schedule: any) => {
  isEditMode.value = true;
  selectedSchedule.value = { ...schedule };
  isModalOpen.value = true;

  console.groupCollapsed('【打开编辑排班弹窗】');
  console.log('编辑的排班ID:', schedule.shiftId);
  console.log('编辑的排班数据:', schedule);
  console.groupEnd();
};

const closeModal = () => {
  isModalOpen.value = false;

  console.log('【关闭排班弹窗】');
};

const saveSchedule = async (data: any) => {
  try {
    // 合并开始时间和结束时间为时间段
    if (data.startTime && data.endTime) {
      data.timeRange = `${data.startTime}-${data.endTime}`;
    }

    if (isEditMode.value) {
      const response = await api.put(`${API_BASE_URL}/shifts/${data.shiftId}`, data);
      const index = scheduleList.value.findIndex(s => s.shiftId === data.shiftId);
      if (index !== -1) scheduleList.value[index] = response.data;

      console.groupCollapsed('【更新排班成功】');
      console.log('更新的排班ID:', data.shiftId);
      console.log('更新后的数据:', response.data);
      console.groupEnd();
    } else {
      const response = await api.post(`${API_BASE_URL}/shifts`, data);
      scheduleList.value.unshift(response.data);

      console.groupCollapsed('【添加排班成功】');
      console.log('新排班ID:', response.data.shiftId);
      console.log('新排班数据:', response.data);
      console.groupEnd();
    }
    closeModal();
  } catch (error) {
    console.error('保存排班信息失败:', error);
  }
};

const deleteSchedule = async (id: number) => {
  if (confirm('确定要删除此排班记录吗？')) {
    try {
      await api.delete(`${API_BASE_URL}/shifts/${id}`);
      scheduleList.value = scheduleList.value.filter(s => s.shiftId !== id);

      console.log(`【删除排班成功，ID: ${id}】`);

      if (paginatedSchedules.value.length === 0 && currentPage.value > 1) {
        currentPage.value--;
      }
    } catch (error) {
      console.error('删除排班信息失败:', error);
    }
  }
};

// 格式化时间范围显示
const formatTimeRange = (schedule: any) => {
  // 优先使用 startTime 和 endTime
  if (schedule.startTime && schedule.endTime) {
    return `${schedule.startTime}-${schedule.endTime}`;
  }

  // 其次使用 timeRange 字段
  if (schedule.timeRange) {
    return schedule.timeRange;
  }

  // 备用显示
  return '未设置时间';
};

const exportToExcel = () => {
  const header = ['班次名称', '日期', '时间', '排班人员', '地点/区域', '任务描述'];
  const dataToExport = filteredSchedules.value.map(s =>([
    s.shiftName,
    s.date,
    formatTimeRange(s),
    s.officerNames.join('、'),
    s.location,
    s.taskDescription
  ]));
  const worksheet = XLSX.utils.aoa_to_sheet([header, ...dataToExport]);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '排班表');
  XLSX.writeFile(workbook, `排班表_${new Date().toLocaleDateString().replace(/\//g, '-')}.xlsx`);

  console.log('【导出排班表成功】');
};
</script>

<style scoped>
@import "@/assets/styles/views/admin/SchedulingManagement.css";
</style>
